package user

import (
	"errors"
	domain "furniture-server-gin/api/pkg/domain/user"

	"golang.org/x/crypto/bcrypt"
)

var (
	ErrUserNotFound    = errors.New("user not found")
	ErrInvalidPassword = errors.New("invalid password")
)

// Service 用户应用服务
type Service struct {
	repo domain.Repository
}

// NewService 创建用户服务
func NewService(repo domain.Repository) *Service {
	return &Service{
		repo: repo,
	}
}

// RegisterUser 注册用户
func (s *Service) RegisterUser(username, password, email string) error {
	// 检查用户是否已存在
	if _, err := s.repo.FindByUsername(username); err == nil {
		return errors.New("username already exists")
	}

	// 密码加密
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	// 创建用户
	user := domain.NewUser(username, string(hashedPassword), email)
	return s.repo.Create(user)
}

// AuthenticateUser 验证用户
func (s *Service) AuthenticateUser(username, password string) (*domain.User, error) {
	user, err := s.repo.FindByUsername(username)
	if err != nil {
		return nil, ErrUserNotFound
	}

	// 验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		return nil, ErrInvalidPassword
	}

	return user, nil
}

// GetUserByID 根据ID获取用户
func (s *Service) GetUserByID(id string) (*domain.User, error) {
	return s.repo.FindByID(id)
}

// GetAllUsers 获取所有用户
func (s *Service) GetAllUsers() ([]*domain.User, error) {
	return s.repo.FindAll()
}

// UpdateUser 更新用户
func (s *Service) UpdateUser(id, username, email string) error {
	user, err := s.repo.FindByID(id)
	if err != nil {
		return ErrUserNotFound
	}

	user.Update(username, email)
	return s.repo.Update(user)
}

// DeleteUser 删除用户
func (s *Service) DeleteUser(id string) error {
	return s.repo.Delete(id)
}
